import * as THREE from "three";
// import { OrbitControls } from "three/addons/controls/OrbitControls.js";
// import { Line2 } from 'three/addons/lines/Line2.js';
// import { LineMaterial } from 'three/addons/lines/LineMaterial.js';
// import { LineGeometry } from 'three/addons/lines/LineGeometry.js';
import * as CM from './control_module.js';
import { fa, tr } from "element-plus/es/locales.mjs";

function Oridata2GroupMeshObj(Attributedict,group) {//依据网格属性信息集合，在threejs中创建线单元集合和三角形单元集合并渲染。
    let vertices = Attributedict.pointsarray;
    let colors = Attributedict.colorsarray;
    CM.removeModel(group);//清空group组中所有模型
    // console.log('Line_MeshCreate',Attributedict.meshinfo.NLines);
    pointObjCreate(vertices,colors,group,"Nodes");
    for (let i = 0; i < Attributedict['geometryGroups'].length; i++) {
        var value =  Attributedict['geometryGroups'][i];
        var keyname = value.name
        if (value.type=="lines"){
            lineMeshObjCreate(vertices,value.indices,colors,group,keyname);
        }
        if (value.type=="faces"){
            triangleMeshObjCreate(vertices,value.indices,colors,group,keyname);
        }        
    }
    return 0;
}
//---

function Oridata2groupmesh(Attributedict,group) {//依据网格属性信息集合，在threejs中创建线单元集合和三角形单元集合,形成一个整体组别并渲染。
    let vertices = new Float32Array(Attributedict.pointsarray);
    let colors = new Float32Array(Attributedict.colorsarray);
    // CM.removeModel(scene);//清空scene场景中所有模型
    // console.log(Attributedict['geometryGroups']);
    Group_PointCreate(vertices,colors,group,"Nodes");
    for (let i = 0; i < Attributedict['geometryGroups'].length; i++) {
        var value =  Attributedict['geometryGroups'][i];
        var keyname = value.name
        if (value.type=="lines"){
            Group_LineMeshCreate(vertices,value.indices,colors,group,keyname);
        }
        if (value.type=="faces"){
            Group_TriMeshCreate(vertices,value.indices,colors,group,keyname);
        }        
    }

    return 0;
}
function Group_TriMeshCreate(nodes,indexArray,colorsarray,group,keyname) {
    var vertices = new THREE.BufferAttribute(nodes, 3);
    var colors = new THREE.BufferAttribute(colorsarray, 3);
    var indices = new THREE.BufferAttribute(new Uint32Array(indexArray), 1);//需要采用Uint32Array来存储更多的顶点数量
    var Tri_geometry = new THREE.BufferGeometry();
    var Tri_material1 = new THREE.MeshBasicMaterial( {
        side: THREE.DoubleSide,
        // color: 0x42a5f5,//控制网格模型的没有节点数据时的默认颜色
        color: 0xCCCCCC,//控制网格模型的没有节点数据时的默认颜色
        vertexColors: false,
        // morphTargets: true
    } );
    // console.log('Tri_material1 color:',Tri_material1.color.getHex());
    var Tri_material2 = new THREE.MeshBasicMaterial( {
        color: 0x000000,//控制网格模型的没有节点数据时的默认颜色
        vertexColors: false,
        wireframe: true,
        // morphTargets: true
    } );
    // Tri_geometry.morphAttributes.position = [];//初始化morph目标数组
    Tri_geometry.setAttribute('position', vertices);
    Tri_geometry.setIndex(indices);
    // Tri_geometry.morphAttributes.position[ 0 ] = vertices;//添加初始位置作为morph目标
    
    Tri_geometry.setAttribute( 'color', colors);
    //geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );
    //-------------
    Tri_geometry.computeVertexNormals();//通过这两句更新顶点法向量更好些
    Tri_geometry.normalsNeedUpdate = true;
    //-------------
    // Tri_geometry.center();
    //console.log(Tri_geometry.toJSON());
    //console.log(JSON.stringify(Tri_geometry));
    // var Tri_mesh = new THREE.Mesh(Tri_geometry, [Tri_material1,Tri_material2]);
    var Tri_mesh = new THREE.Mesh(Tri_geometry, Tri_material1);
    //
    // Tri_mesh.morphTargetInfluences[ 0 ] = 0.0;
    Tri_mesh.name=keyname;
    group.add(Tri_mesh);
    // Tri_mesh.visible = false;//默认不显示
    var Tri_mesh_Frame = new THREE.Mesh(Tri_geometry, Tri_material2);
    //
    // Tri_mesh_Frame.morphTargetInfluences[ 0 ] = 0.0;
    Tri_mesh_Frame.name='meshFrame';
    group.add(Tri_mesh_Frame);
    Tri_mesh_Frame.visible = false;//默认不显示

}
function Group_LineMeshCreate(nodes,indexArray,colorarray,group,keyname) {
    var vertices = new THREE.BufferAttribute(nodes, 3);
    var colors = new THREE.BufferAttribute(colorarray, 3);
    var indices = new THREE.BufferAttribute(new Uint32Array(indexArray), 1);
    var Line_geometry = new THREE.BufferGeometry();
    var Line_material = new THREE.LineBasicMaterial( { vertexColors: false,
        color: 0x000000,
    } );
    // Line_geometry.morphAttributes.position = [];//初始化morph目标数组
    
    Line_geometry.setIndex(indices);
    Line_geometry.setAttribute('position', vertices);
    //-------------
    var Line_mesh = new THREE.LineSegments(Line_geometry, Line_material);
    // 
    Line_mesh.name=keyname;
    group.add(Line_mesh);
    // scene.add(Line_mesh);
}
function Group_PointCreate(nodes,colorarray,group,keyname) {//创建节点
    var vertices = new THREE.BufferAttribute(nodes, 3);
    var colors = new THREE.BufferAttribute(colorarray, 3);
    var Point_geometry = new THREE.BufferGeometry();
    Point_geometry.setAttribute('position', vertices);
    Point_geometry.setAttribute( 'color', colors);
    var Point_material = new THREE.PointsMaterial( {
        size: 1.0,
        vertexColors: true,
    } );
    var Point_mesh = new THREE.Points( Point_geometry, Point_material );
    Point_mesh.name=keyname;
    group.add(Point_mesh);
    Point_mesh.visible = true;//默认不显示
}
//
function pointObjCreate(vertices,colors,group,keyname) {//创建节点

    var Point_geometry = new THREE.BufferGeometry();
    Point_geometry.setAttribute('position', vertices);
    Point_geometry.setAttribute( 'color', colors);
    var Point_material = new THREE.PointsMaterial( {
        size: 1.0,//点的大小不能定死，应该是整体模型盒子的大小的一个比例
        vertexColors: true,
    } );
    var Point_Mesh = new THREE.Points( Point_geometry, Point_material );
    Point_Mesh.name=keyname;
    group.add(Point_Mesh);
    Point_Mesh.visible = false;//默认不显示
}
function triangleMeshObjCreate(vertices,indexArray,colors,group,keyname) {//创建三角形单元部分的threejs网格、几何、材质、添加至渲染器等工作

    var indices = new THREE.BufferAttribute(new Uint32Array(indexArray), 1);//需要采用Uint32Array来存储更多的顶点数量
    var Tri_geometry = new THREE.BufferGeometry();
    var Tri_material = new THREE.MeshBasicMaterial( {
        side: THREE.DoubleSide,
        color: 0xCCCCCC,//控制网格模型的没有节点数据时的默认颜色
        vertexColors: false
    } );    
    
    Tri_geometry.setAttribute('position', vertices);
    Tri_geometry.setIndex(indices);
    Tri_geometry.setAttribute( 'color', colors);
    //geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );
    //-------------
    Tri_geometry.computeVertexNormals();//通过这两句更新顶点法向量更好些
    Tri_geometry.normalsNeedUpdate = true;
    //-------------
    Tri_geometry.center();
    var Triangle_Mesh = new THREE.Mesh(Tri_geometry, Tri_material);
    Triangle_Mesh.name=keyname;
    //-------------
    group.add(Triangle_Mesh);
    // ---------------
    var meshFrameMaterial = new THREE.MeshBasicMaterial( {
        color: 0x000000,//控制网格模型的没有节点数据时的默认颜色
        vertexColors: false,
        wireframe: true,
        // morphTargets: true
    } );
    //-------------
    var triangleMesh_Frame = new THREE.Mesh(Tri_geometry, meshFrameMaterial);
    triangleMesh_Frame.name='meshFrame';
    group.add(triangleMesh_Frame);
    triangleMesh_Frame.visible = true;//默认不显示
    return 0;
}
//
function lineMeshObjCreate(vertices,indexArray,colors,group,keyname) {//根据顶点对象、索引数组、颜色对象创建线单元部分的threejs网格、几何、材质、添加至组
    var indices = new THREE.BufferAttribute(new Uint32Array(indexArray), 1);
    var Line_geometry = new THREE.BufferGeometry();
    // var Line_material = new THREE.LineBasicMaterial( { vertexColors: true} );
    var Line_material = new THREE.LineBasicMaterial( { vertexColors: false,
        color: 0x000000,
    } );
    Line_geometry.setIndex(indices);
    Line_geometry.setAttribute('position', vertices);
    //-------------
    Line_geometry.setAttribute( 'color', colors);
    Line_geometry.center();
    //-------------
    //console.log(JSON.stringify(Tri_geometry));    
    var Line_Mesh = new THREE.LineSegments(Line_geometry, Line_material);
    Line_Mesh.name=keyname;
    //-------------
    group.add(Line_Mesh);
    return 0;

}
//

function createRectShapeVertice(centerX, centerY, width, height,clockwise=true) {
    // 计算半宽、半高（中心点到边的偏移量）
  const halfWidth = width / 2;
  const halfHeight = height / 2;

  // 计算4个顶点的绝对坐标（按顺时针顺序）
  const points = [
    { x: centerX - halfWidth, y: centerY + halfHeight }, // 左上角
    { x: centerX + halfWidth, y: centerY + halfHeight }, // 右上角
    { x: centerX + halfWidth, y: centerY - halfHeight }, // 右下角
    { x: centerX - halfWidth, y: centerY - halfHeight }  // 左下角
  ];
  if (!clockwise) {
    // 逆时针方向
    points.reverse();
  }
  return points;
}
function createRectShape(centerX, centerY, width, height,clockwise=true) {
  // 创建Shape并连接顶点
  const points = createRectShapeVertice(centerX, centerY, width, height,clockwise);
  const rectShape = createPolyShape(points);
// 
  return rectShape;
}
function createCircleShapeVertice(centerX, centerY, radius, segments = 32,clockwise=true) {

  // 避免分段数过少导致形状失真（最小8段）
  segments = Math.max(segments, 8);

  // 计算每段的角度增量（2π = 360°，分成segments等份）
  const angleStep = (2 * Math.PI) / segments;
  const points = [];
  

  // 循环计算其余顶点（从第0段到最后1段）
  for (let i = 0; i < segments; i++) {
    const angle = i * angleStep; // 当前角度
    const x = centerX + radius * Math.cos(angle);
    const y = centerY + radius * Math.sin(angle);
    points.push({ x: x, y: y });
  }
  if (!clockwise) {
    // 逆时针方向
    points.reverse();
  }
  return points;
}
function createCircleShape(centerX, centerY, radius, segments = 32,clockwise=true) {
  
  const points = createCircleShapeVertice(centerX, centerY, radius, segments,clockwise);
  const circleShape = createPolyShape(points);

  return circleShape;
}
function createRingShape(centerX, centerY, outerRadius, innerRadius, segments = 32) {
  // 外圆Shape（主体）
  const ringShape = createCircleShape(centerX, centerY, outerRadius, segments);
  
  // 内圆Path（空心区域，需与外圆顶点顺序相反，避免冲突）
  const innerCircleVertice = createCircleShapeVertice(centerX, centerY, innerRadius, segments,false);
//   console.log(innerCircleVertice);
  const innerCirclePath = new THREE.Path();
// 
  innerCirclePath.moveTo(innerCircleVertice[0].x, innerCircleVertice[0].y);
  
  // 内圆顶点按逆时针顺序（与外圆顺时针相反）
  for (let i = 1; i < segments; i++) {
	innerCirclePath.lineTo(innerCircleVertice[i].x, innerCircleVertice[i].y);
  }
  innerCirclePath.closePath();
  // 将内圆Path设为外圆Shape的空心区域
  ringShape.holes.push(innerCirclePath);
  return ringShape;
}
function createBoxShape(centerX, centerY, outerWidth, outerHeight, thickness) {
  // 外方Shape（主体）
  const boxShape = createRectShape(centerX, centerY, outerWidth, outerHeight);
  
  // 内方Path（空心区域，需与外圆顶点顺序相反，避免冲突）
  const innerRectVertice = createRectShapeVertice(centerX, centerY, outerWidth - 2*thickness, outerHeight - 2*thickness,false);
//   console.log(innerCircleVertice);
  const innerRectPath = new THREE.Path();
// 
  innerRectPath.moveTo(innerRectVertice[0].x, innerRectVertice[0].y);
  
  // 内方顶点按逆时针顺序（与外方顺时针相反）
  for (let i = 1; i < innerRectVertice.length; i++) {
	innerRectPath.lineTo(innerRectVertice[i].x, innerRectVertice[i].y);
  }
  innerRectPath.closePath();
  // 将内方Path设为外方Shape的空心区域
  boxShape.holes.push(innerRectPath);
  return boxShape;
}
function createPolyShape(points) {
  // 创建Shape并连接顶点
  const polyShape = new THREE.Shape();
  // 移动到第一个顶点（左上角）
  polyShape.moveTo(points[0].x, points[0].y);
  
  // 依次连接其他顶点
    for (let i = 1; i < points.length; i++) {
    const x = points[i].x;
    const y = points[i].y;
    polyShape.lineTo(x, y); // 连接到当前顶点
  }
  // 闭合形状（最后一个顶点 → 第一个顶点，也可省略，Shape会自动闭合）
  polyShape.closePath();
  return polyShape;
}
export{Oridata2GroupMeshObj,Oridata2groupmesh,createRectShape,createCircleShape,createRingShape,createBoxShape,createPolyShape};